// getCrombs(): Retrieve crombs located at the current position - Returns array of object Crombs
// getCrombsCount(): Retrieve crombs count at the current postion without loading content - Returns integer
// getCrombsClosest(): Retreives the distance to the closest cromb beyond current position - Returns distance in meters

//Object
function Cromb(){
  this.author = null;
  this.message = null;
  this.datetime = null;
  this.distance = null;
}
function getCrombs()
{
  var xmlhttp;
  var txt,i;
  if(!isGPSEnabled()){
     makeAlert("Can You Enable GPS In Your Devices Settings Please?")
     return []; //MUST RETURN A EMPTY ARRAY TO PREVENT RENDERERS.JS FROM CRASHING
  }

  var url = "scripts/crombsDAO.php?lon="+gpsLongitude+"&lat="+gpsLatitude+"&action=getcrombs";
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  var crombs = new Array(0);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState===4 && xmlhttp.status===200){
      var parser = new DOMParser();
      var x = parser.parseFromString(xmlhttp.responseText.trim(), "text/xml").getElementsByTagName("cromb");
      crombs = new Array(x.length);
      for (i=0;i<x.length;i++){
        var author=x[i].getAttribute("author");
        var datetime=x[i].getAttribute("date");
        var message=x[i].childNodes[0].nodeValue;
        var dist = x[i].getAttribute("dist");
        var cromb = new Cromb();
        cromb.author = author;
        cromb.datetime = renderDatetime(datetime);
        cromb.message = replaceURLWithHTMLLinks(message);
        cromb.distance = dist;
        crombs[i]=cromb;
      }
    }
  };
  xmlhttp.open("POST",url,false);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  xmlhttp.overrideMimeType('text/xml');
  xmlhttp.send();
  return crombs;
}
function getCrombsCount()
{
  var xmlhttp;
  var txt,i;
  if(!isGPSEnabled()){
     return;
  }

  var url = "scripts/crombsDAO.php?lon="+gpsLongitude+"&lat="+gpsLatitude+"&action=scancromb";
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  var count = 0;
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState===4 && xmlhttp.status===200){
      var parser = new DOMParser();
      var x = parser.parseFromString(xmlhttp.responseText.trim(), "text/xml").getElementsByTagName("crombscan");
      //There should be only one...
      for (i=0;i<x.length;i++){
        count=x[i].getAttribute("count");
        
      }
    }
  };
  xmlhttp.open("POST",url,false);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  xmlhttp.overrideMimeType('text/xml');
  xmlhttp.send();
  return count;
}
function getCrombsClosest()
{
  var xmlhttp;
  var txt,i;
  if(!isGPSEnabled()){
     return undefined;
  }

  var url = "scripts/crombsDAO.php?lon="+gpsLongitude+"&lat="+gpsLatitude+"&action=getcrombsclosest";
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  var distance = 0;
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState===4 && xmlhttp.status===200){
      var parser = new DOMParser();
      var x = parser.parseFromString(xmlhttp.responseText.trim(), "text/xml").getElementsByTagName("crombsclosest");
      //There should be only one...
      for (i=0;i<x.length;i++){
        distance=x[i].getAttribute("distance");
        
      }
    }
  };
  xmlhttp.open("POST",url,false);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  xmlhttp.overrideMimeType('text/xml');
  xmlhttp.send();
  return distance;
}
function putCromb(author,message){
  if(!isGPSEnabled()){
     return false;
  } else {
    if (message !== null && author!=null) {
      message = message.replace(/(<([^>]+)>)/ig, "");
      author = author.replace(/(<([^>]+)>)/ig, "");
      var url = "crombsDAO.php?author=" + encodeURIComponent(author) + "&lon=" + gpsLongitude + "&lat=" + gpsLatitude + "&message=" + encodeURIComponent(message)+"&action=putcromb";
      var xmlhttp;
      if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
      else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.open("POST",url,false);
      xmlhttp.setRequestHeader("Content-Type","text/xml");
      xmlhttp.overrideMimeType('text/xml');
      xmlhttp.send();
      return true;
    }
  }                     
}

//Crombs Related End

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
}

function renderDatetime(stringDT){
  return new Date(stringDT.replace(" ", "T")+".000Z").toLocaleString();
}

function renderDistance(distance){
 if (distance === undefined){
   return "NA";
 }
 if (distance >= 1000){
    return Math.round(distance/100)/10+"km";
 } else {
    return Math.round(distance*10)/10+"m";
 }
}
